use async_trait::async_trait;
use rustcloud_core::{ServiceResult, ServiceError};
use crate::collector::{MetricsCollector, MetricType, MetricValue};
use crate::logging::{LogAggregator, LogLevel, LogFilter};
use crate::tracing::TraceExporter;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH, Duration};
use tokio::sync::RwLock;

/// 性能指标枚举
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PerformanceMetric {
    /// 响应时间（毫秒）
    ResponseTime,
    /// CPU使用率（百分比）
    CpuUsage,
    /// 内存使用率（百分比）
    MemoryUsage,
    /// 错误率（百分比）
    ErrorRate,
    /// 请求速率（每秒请求数）
    RequestRate,
    /// 活跃连接数
    ActiveConnections,
    /// 队列长度
    QueueLength,
    /// 磁盘IO使用率
    DiskIoUsage,
    /// 网络IO使用率
    NetworkIoUsage,
}

impl PerformanceMetric {
    /// 转换为字符串
    pub fn to_string(&self) -> String {
        match self {
            PerformanceMetric::ResponseTime => "response_time_ms".to_string(),
            PerformanceMetric::CpuUsage => "cpu_usage_percent".to_string(),
            PerformanceMetric::MemoryUsage => "memory_usage_percent".to_string(),
            PerformanceMetric::ErrorRate => "error_rate_percent".to_string(),
            PerformanceMetric::RequestRate => "request_rate_per_second".to_string(),
            PerformanceMetric::ActiveConnections => "active_connections".to_string(),
            PerformanceMetric::QueueLength => "queue_length".to_string(),
            PerformanceMetric::DiskIoUsage => "disk_io_usage_percent".to_string(),
            PerformanceMetric::NetworkIoUsage => "network_io_usage_percent".to_string(),
        }
    }
}

/// 性能阈值定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceThreshold {
    /// 指标类型
    pub metric: PerformanceMetric,
    /// 警告阈值
    pub warning_threshold: f64,
    /// 错误阈值
    pub error_threshold: f64,
    /// 致命阈值
    pub critical_threshold: f64,
    /// 检查窗口期（秒）
    pub window_seconds: u64,
    /// 连续触发次数
    pub consecutive_violations: u32,
}

impl Default for PerformanceThreshold {
    fn default() -> Self {
        Self {
            metric: PerformanceMetric::ResponseTime,
            warning_threshold: 1000.0,  // 1秒
            error_threshold: 3000.0,    // 3秒
            critical_threshold: 5000.0, // 5秒
            window_seconds: 60,         // 1分钟窗口
            consecutive_violations: 3,   // 连续3次
        }
    }
}

/// 告警级别
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum AlertLevel {
    /// 信息级别
    Info = 0,
    /// 警告级别
    Warning = 1,
    /// 错误级别
    Error = 2,
    /// 致命级别
    Critical = 3,
}

impl AlertLevel {
    pub fn to_string(&self) -> String {
        match self {
            AlertLevel::Info => "INFO".to_string(),
            AlertLevel::Warning => "WARNING".to_string(),
            AlertLevel::Error => "ERROR".to_string(),
            AlertLevel::Critical => "CRITICAL".to_string(),
        }
    }
}

/// 告警事件
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertEvent {
    /// 告警ID
    pub id: String,
    /// 告警级别
    pub level: AlertLevel,
    /// 告警标题
    pub title: String,
    /// 告警描述
    pub description: String,
    /// 服务名称
    pub service_name: String,
    /// 实例ID
    pub instance_id: String,
    /// 指标类型
    pub metric: PerformanceMetric,
    /// 当前值
    pub current_value: f64,
    /// 阈值
    pub threshold: f64,
    /// 触发时间
    pub timestamp: u64,
    /// 附加标签
    pub labels: HashMap<String, String>,
    /// 状态（触发/恢复）
    pub status: AlertStatus,
}

/// 告警状态
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AlertStatus {
    /// 触发
    Triggered,
    /// 恢复
    Resolved,
}

impl AlertEvent {
    /// 创建新的告警事件
    pub fn new(
        level: AlertLevel,
        title: String,
        description: String,
        service_name: String,
        instance_id: String,
        metric: PerformanceMetric,
        current_value: f64,
        threshold: f64,
    ) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            level,
            title,
            description,
            service_name,
            instance_id,
            metric,
            current_value,
            threshold,
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
            labels: HashMap::new(),
            status: AlertStatus::Triggered,
        }
    }

    /// 添加标签
    pub fn with_label(mut self, key: &str, value: &str) -> Self {
        self.labels.insert(key.to_string(), value.to_string());
        self
    }

    /// 设置为已恢复状态
    pub fn resolve(mut self) -> Self {
        self.status = AlertStatus::Resolved;
        self.timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        self
    }
}

/// 性能监控数据点
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceDataPoint {
    /// 时间戳
    pub timestamp: u64,
    /// 指标类型
    pub metric: PerformanceMetric,
    /// 指标值
    pub value: f64,
    /// 服务名称
    pub service_name: String,
    /// 实例ID
    pub instance_id: String,
    /// 标签
    pub labels: HashMap<String, String>,
}

impl PerformanceDataPoint {
    pub fn new(
        metric: PerformanceMetric,
        value: f64,
        service_name: String,
        instance_id: String,
    ) -> Self {
        Self {
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_micros() as u64,
            metric,
            value,
            service_name,
            instance_id,
            labels: HashMap::new(),
        }
    }

    pub fn with_label(mut self, key: &str, value: &str) -> Self {
        self.labels.insert(key.to_string(), value.to_string());
        self
    }
}

/// 告警处理器trait
#[async_trait]
pub trait AlertHandler: Send + Sync {
    /// 处理告警事件
    async fn handle_alert(&self, alert: AlertEvent) -> ServiceResult<()>;
    
    /// 获取处理器名称
    fn name(&self) -> &str;
}

/// 日志告警处理器
pub struct LogAlertHandler {
    name: String,
    log_aggregator: Arc<dyn LogAggregator>,
}

impl LogAlertHandler {
    pub fn new(name: String, log_aggregator: Arc<dyn LogAggregator>) -> Self {
        Self {
            name,
            log_aggregator,
        }
    }
}

#[async_trait]
impl AlertHandler for LogAlertHandler {
    async fn handle_alert(&self, alert: AlertEvent) -> ServiceResult<()> {
        use crate::logging::LogEntry;
        use serde_json::Value;

        let log_level = match alert.level {
            AlertLevel::Info => LogLevel::Info,
            AlertLevel::Warning => LogLevel::Warn,
            AlertLevel::Error => LogLevel::Error,
            AlertLevel::Critical => LogLevel::Fatal,
        };

        let message = format!(
            "[{}] {} - {}: {} (当前值: {}, 阈值: {})",
            alert.level.to_string(),
            alert.title,
            alert.service_name,
            alert.description,
            alert.current_value,
            alert.threshold
        );

        let mut entry = LogEntry::new(
            log_level,
            message,
            alert.service_name.clone(),
            alert.instance_id.clone(),
        );

        // 添加告警相关字段
        entry.fields.insert("alert_id".to_string(), Value::String(alert.id));
        entry.fields.insert("alert_level".to_string(), Value::String(alert.level.to_string()));
        entry.fields.insert("metric_type".to_string(), Value::String(alert.metric.to_string()));
        entry.fields.insert("current_value".to_string(), Value::Number(
            serde_json::Number::from_f64(alert.current_value).unwrap_or_else(|| serde_json::Number::from(0))
        ));
        entry.fields.insert("threshold".to_string(), Value::Number(
            serde_json::Number::from_f64(alert.threshold).unwrap_or_else(|| serde_json::Number::from(0))
        ));
        entry.fields.insert("status".to_string(), Value::String(
            match alert.status {
                AlertStatus::Triggered => "triggered".to_string(),
                AlertStatus::Resolved => "resolved".to_string(),
            }
        ));

        // 添加标签
        for (key, value) in alert.labels {
            entry.tags.insert(key, value);
        }

        self.log_aggregator.append(entry).await
    }

    fn name(&self) -> &str {
        &self.name
    }
}

/// 控制台告警处理器
pub struct ConsoleAlertHandler {
    name: String,
    colored: bool,
}

impl ConsoleAlertHandler {
    pub fn new(name: String, colored: bool) -> Self {
        Self { name, colored }
    }

    fn colorize_level(&self, level: &AlertLevel) -> String {
        if !self.colored {
            return level.to_string();
        }

        match level {
            AlertLevel::Info => format!("\x1b[36m{}\x1b[0m", level.to_string()),    // 青色
            AlertLevel::Warning => format!("\x1b[33m{}\x1b[0m", level.to_string()), // 黄色
            AlertLevel::Error => format!("\x1b[31m{}\x1b[0m", level.to_string()),   // 红色
            AlertLevel::Critical => format!("\x1b[35m{}\x1b[0m", level.to_string()), // 紫色
        }
    }
}

#[async_trait]
impl AlertHandler for ConsoleAlertHandler {
    async fn handle_alert(&self, alert: AlertEvent) -> ServiceResult<()> {
        let timestamp = chrono::DateTime::from_timestamp(alert.timestamp as i64, 0)
            .unwrap_or_default()
            .format("%Y-%m-%d %H:%M:%S");

        let status_indicator = match alert.status {
            AlertStatus::Triggered => "🚨",
            AlertStatus::Resolved => "✅",
        };

        println!(
            "{} {} [{}] {}/{}: {} - {} (当前值: {:.2}, 阈值: {:.2})",
            timestamp,
            status_indicator,
            self.colorize_level(&alert.level),
            alert.service_name,
            alert.instance_id,
            alert.title,
            alert.description,
            alert.current_value,
            alert.threshold
        );

        Ok(())
    }

    fn name(&self) -> &str {
        &self.name
    }
}

/// HTTP告警处理器
pub struct HttpAlertHandler {
    name: String,
    webhook_url: String,
    client: reqwest::Client,
    headers: HashMap<String, String>,
}

impl HttpAlertHandler {
    pub fn new(name: String, webhook_url: String) -> Self {
        Self {
            name,
            webhook_url,
            client: reqwest::Client::new(),
            headers: HashMap::new(),
        }
    }

    pub fn with_header(mut self, key: &str, value: &str) -> Self {
        self.headers.insert(key.to_string(), value.to_string());
        self
    }
}

#[async_trait]
impl AlertHandler for HttpAlertHandler {
    async fn handle_alert(&self, alert: AlertEvent) -> ServiceResult<()> {
        let payload = serde_json::to_string(&alert)
            .map_err(|e| ServiceError::MetricsError(format!("序列化告警失败: {}", e)))?;

        let mut request = self.client
            .post(&self.webhook_url)
            .header("Content-Type", "application/json")
            .body(payload);

        for (key, value) in &self.headers {
            request = request.header(key, value);
        }

        let response = request
            .send()
            .await
            .map_err(|e| ServiceError::MetricsError(format!("发送HTTP告警失败: {}", e)))?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            return Err(ServiceError::MetricsError(format!(
                "HTTP告警发送失败 {}: {}", status, body
            )));
        }

        Ok(())
    }

    fn name(&self) -> &str {
        &self.name
    }
}

/// 性能监控器
pub struct PerformanceMonitor {
    service_name: String,
    instance_id: String,
    thresholds: Arc<RwLock<HashMap<PerformanceMetric, PerformanceThreshold>>>,
    alert_handlers: Arc<RwLock<Vec<Arc<dyn AlertHandler>>>>,
    metrics_collector: Arc<dyn MetricsCollector>,
    data_points: Arc<RwLock<Vec<PerformanceDataPoint>>>,
    violation_counts: Arc<RwLock<HashMap<PerformanceMetric, u32>>>,
    max_data_points: usize,
}

impl PerformanceMonitor {
    pub fn new(
        service_name: String,
        instance_id: String,
        metrics_collector: Arc<dyn MetricsCollector>,
        max_data_points: usize,
    ) -> Self {
        Self {
            service_name,
            instance_id,
            thresholds: Arc::new(RwLock::new(HashMap::new())),
            alert_handlers: Arc::new(RwLock::new(Vec::new())),
            metrics_collector,
            data_points: Arc::new(RwLock::new(Vec::new())),
            violation_counts: Arc::new(RwLock::new(HashMap::new())),
            max_data_points,
        }
    }

    /// 添加性能阈值
    pub async fn add_threshold(&self, threshold: PerformanceThreshold) {
        let mut thresholds = self.thresholds.write().await;
        thresholds.insert(threshold.metric.clone(), threshold);
    }

    /// 添加告警处理器
    pub async fn add_alert_handler(&self, handler: Arc<dyn AlertHandler>) {
        let mut handlers = self.alert_handlers.write().await;
        handlers.push(handler);
    }

    /// 记录性能数据点
    pub async fn record_metric(
        &self,
        metric: PerformanceMetric,
        value: f64,
        labels: HashMap<String, String>,
    ) -> ServiceResult<()> {
        let metric_name = metric.to_string();
        
        // 确保指标已注册
        if let Err(_) = self.metrics_collector.record_counter(&metric_name, value, labels.clone()).await {
            // 如果没有注册，先注册再记录
            self.metrics_collector.register_metric(
                &metric_name,
                &format!("性能指标: {}", metric_name),
                crate::collector::MetricType::Counter,
                HashMap::new(),
            ).await?;
            
            self.metrics_collector.record_counter(&metric_name, value, labels.clone()).await?;
        }

        // 创建数据点
        let mut data_point = PerformanceDataPoint::new(
            metric.clone(),
            value,
            self.service_name.clone(),
            self.instance_id.clone(),
        );
        for (key, val) in labels {
            data_point = data_point.with_label(&key, &val);
        }

        // 存储数据点
        {
            let mut data_points = self.data_points.write().await;
            data_points.push(data_point);
            
            // 限制数据点数量
            if data_points.len() > self.max_data_points {
                let excess = data_points.len() - self.max_data_points;
                data_points.drain(0..excess);
            }
        }

        // 检查阈值
        self.check_thresholds(&metric, value).await?;

        Ok(())
    }

    /// 检查阈值并触发告警
    async fn check_thresholds(&self, metric: &PerformanceMetric, value: f64) -> ServiceResult<()> {
        let thresholds = self.thresholds.read().await;
        let threshold = match thresholds.get(metric) {
            Some(t) => t.clone(),
            None => return Ok(()), // 没有配置阈值
        };
        drop(thresholds);

        let mut alert_level = None;
        let mut threshold_value = 0.0;

        // 判断告警级别
        if value >= threshold.critical_threshold {
            alert_level = Some(AlertLevel::Critical);
            threshold_value = threshold.critical_threshold;
        } else if value >= threshold.error_threshold {
            alert_level = Some(AlertLevel::Error);
            threshold_value = threshold.error_threshold;
        } else if value >= threshold.warning_threshold {
            alert_level = Some(AlertLevel::Warning);
            threshold_value = threshold.warning_threshold;
        }

        if let Some(level) = alert_level {
            // 检查连续违规次数
            let mut violation_counts = self.violation_counts.write().await;
            let count = violation_counts.entry(metric.clone()).or_insert(0);
            *count += 1;

            if *count >= threshold.consecutive_violations {
                // 触发告警
                let alert = AlertEvent::new(
                    level.clone(),
                    format!("{} 超过阈值", metric.to_string()),
                    format!(
                        "指标 {} 连续 {} 次超过 {} 阈值，当前值: {:.2}",
                        metric.to_string(),
                        threshold.consecutive_violations,
                        level.to_string(),
                        value
                    ),
                    self.service_name.clone(),
                    self.instance_id.clone(),
                    metric.clone(),
                    value,
                    threshold_value,
                );

                self.send_alert(alert).await?;
                *count = 0; // 重置计数
            }
        } else {
            // 重置违规计数
            let mut violation_counts = self.violation_counts.write().await;
            violation_counts.remove(metric);
        }

        Ok(())
    }

    /// 发送告警
    async fn send_alert(&self, alert: AlertEvent) -> ServiceResult<()> {
        let handlers = self.alert_handlers.read().await;
        for handler in handlers.iter() {
            if let Err(e) = handler.handle_alert(alert.clone()).await {
                eprintln!("告警处理器 {} 处理失败: {}", handler.name(), e);
            }
        }
        Ok(())
    }

    /// 获取性能统计信息
    pub async fn get_performance_stats(&self) -> PerformanceStats {
        let data_points = self.data_points.read().await;
        let mut stats = PerformanceStats::default();
        
        stats.total_data_points = data_points.len();
        
        // 按指标类型统计
        for point in data_points.iter() {
            let metric_stats = stats.metric_stats.entry(point.metric.clone()).or_insert(MetricStats::default());
            metric_stats.count += 1;
            metric_stats.sum += point.value;
            metric_stats.min = metric_stats.min.min(point.value);
            metric_stats.max = metric_stats.max.max(point.value);
        }

        // 计算平均值
        for metric_stat in stats.metric_stats.values_mut() {
            if metric_stat.count > 0 {
                metric_stat.avg = metric_stat.sum / metric_stat.count as f64;
            }
        }

        stats
    }

    /// 获取指定时间范围内的数据点
    pub async fn get_data_points_in_range(
        &self,
        metric: Option<PerformanceMetric>,
        start_time: u64,
        end_time: u64,
    ) -> Vec<PerformanceDataPoint> {
        let data_points = self.data_points.read().await;
        data_points
            .iter()
            .filter(|point| {
                let time_in_range = point.timestamp >= start_time && point.timestamp <= end_time;
                let metric_match = metric.as_ref().map_or(true, |m| &point.metric == m);
                time_in_range && metric_match
            })
            .cloned()
            .collect()
    }

    /// 清空数据点
    pub async fn clear_data_points(&self) {
        let mut data_points = self.data_points.write().await;
        data_points.clear();
    }
}

/// 性能统计信息
#[derive(Debug, Default)]
pub struct PerformanceStats {
    pub total_data_points: usize,
    pub metric_stats: HashMap<PerformanceMetric, MetricStats>,
}

/// 指标统计信息
#[derive(Debug)]
pub struct MetricStats {
    pub count: usize,
    pub sum: f64,
    pub avg: f64,
    pub min: f64,
    pub max: f64,
}

impl Default for MetricStats {
    fn default() -> Self {
        Self {
            count: 0,
            sum: 0.0,
            avg: 0.0,
            min: f64::MAX,
            max: f64::MIN,
        }
    }
}

/// 健康检查监控器
pub struct HealthCheckMonitor {
    service_name: String,
    instance_id: String,
    performance_monitor: Arc<PerformanceMonitor>,
}

impl HealthCheckMonitor {
    pub fn new(
        service_name: String,
        instance_id: String,
        performance_monitor: Arc<PerformanceMonitor>,
    ) -> Self {
        Self {
            service_name,
            instance_id,
            performance_monitor,
        }
    }

    /// 执行健康检查
    pub async fn check_health(&self) -> ServiceResult<HealthStatus> {
        let start_time = std::time::Instant::now();
        
        // 模拟健康检查逻辑
        let is_healthy = self.perform_health_checks().await?;
        
        let duration = start_time.elapsed();
        
        // 记录响应时间
        self.performance_monitor.record_metric(
            PerformanceMetric::ResponseTime,
            duration.as_millis() as f64,
            HashMap::new(),
        ).await?;

        let status = if is_healthy {
            HealthStatus::Healthy
        } else {
            HealthStatus::Unhealthy
        };

        Ok(status)
    }

    /// 执行具体的健康检查
    async fn perform_health_checks(&self) -> ServiceResult<bool> {
        // 这里可以添加具体的健康检查逻辑
        // 例如：数据库连接检查、外部服务检查等
        
        // 模拟检查
        tokio::time::sleep(Duration::from_millis(10)).await;
        
        // 简单返回健康状态
        Ok(true)
    }
}

/// 健康状态枚举
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum HealthStatus {
    /// 健康
    Healthy,
    /// 不健康
    Unhealthy,
    /// 降级
    Degraded,
}

impl HealthStatus {
    pub fn to_string(&self) -> String {
        match self {
            HealthStatus::Healthy => "healthy".to_string(),
            HealthStatus::Unhealthy => "unhealthy".to_string(),
            HealthStatus::Degraded => "degraded".to_string(),
        }
    }
}